﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Speech.Synthesis;
using System.Threading;
using System.Windows.Forms;
using Timer = System.Timers.Timer;

namespace osu_BeatmapAutoLoader
{
    public delegate void GetSetIdEventHandler(string beatmapId);
    public delegate void CancelDownloadEventHander(string beatmapId);
    public delegate void InjectFailedEventHander();

    public class InjectInterface : MarshalByRefObject
    {
        public  Timer WatchDog = new Timer(1000);
        private  bool _injectFlag;
        private readonly SpeechSynthesizer synth = new SpeechSynthesizer();
        public static event GetSetIdEventHandler GetBeatmapId;
        public static event InjectFailedEventHander InjectFailed;
        public static event CancelDownloadEventHander onCancelDownload;


        public void IsInstalled(Int32 InClientPID)
        {
            synth.Volume = 100;
            synth.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Adult, 0, new CultureInfo("en-us"));
            Program.Mainform.Info_Notification("Inject Success", "osu!BeatmapAutoLoader is running at " + InClientPID);
            synth.SpeakAsync("Injector Online!");
            _injectFlag = true;
            WatchDog.Elapsed += (sender, args) =>
            {
                if (_injectFlag)
                {
                    _injectFlag = false;
                }
                else
                {
                    WatchDog.Stop();
                    Process[] osu = Process.GetProcessesByName("osu!");
                    if (!osu.Any())
                    {
                        synth.SpeakAsync("See you!");
                        Program.Mainform.Info_Notification("Exit", "Bye Bye！");
                        Thread.Sleep(2000);
                        Application.Exit();
                    }
                    else
                    {
                        synth.Speak("Injector Offline!");
                        osu[0].Close();
                        if (InjectFailed != null) InjectFailed();
                    }
                }
            };
            WatchDog.Start();
        }

        public void OnGetBeatmapId(string beatmapId)
        {
            if (GetBeatmapId != null) GetBeatmapId(beatmapId);
        }

        public void ReportException(Exception inInfo)
        {
            Program.Mainform.AddLog("Inject Failed：" + inInfo);
            Program.Mainform.Error_Notification("Inject Failed", "osu!BeatmapAutoLoader is NOT running...");
        }

        public void CancelDownload(string beatmapId)
        {
            if (onCancelDownload != null) onCancelDownload(beatmapId);
        }

        public void Ping()
        {
            _injectFlag = true;
        }
    }

}